package com.example.commen.utile

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import com.blankj.utilcode.util.ActivityUtils
import com.example.commen.view.NetWorkDialog


/**
 * @author zyju
 * @date 2024/4/10 13:08
 */
class NetworkBroadcastReceiver : BroadcastReceiver() {
    var dialog: NetWorkDialog = NetWorkDialog()
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == null) {
            return
        }
        if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                // 网络连接可用
                val networkType = activeNetworkInfo.typeName
                Log.d("NetworkChangeReceiver", "Connected to $networkType")
                if (dialog.isShowing)
                    dialog.dismiss()
            } else {
                var activity = ActivityUtils.getTopActivity()
                dialog.show((activity as AppCompatActivity).supportFragmentManager, "")
                // 网络连接不可用
                Log.d("NetworkChangeReceiver", "No network connection available")
            }
        }
    }
}